<?php
$perm = &$AppUI->acl();
if (!$perm->userHasRole($AppUI->user_id, 'Operation')) {
	header('Content-Type: text/xml');

	$xml = new XmlWriter();
	$xml->openMemory();
	$xml->startDocument('1.0', 'UTF-8');
	
	$xml->startElement('root');
	
	$xml->writeElement('success', 'false');
	$xml->writeElement('messages', 'You don\'t have Operation role to update tasks');
	
	$xml->endElement();
	
	echo $xml->outputMemory(true);
	exit;
}
$arr = xml2Array("/root", $_POST['xml']);
$results = array('success' => TRUE, 'messages' => array());
$updateIds = array();
if (count($arr['item']) > 0) {
	if (!is_array($arr['item'][0])) {
		$tmp = $arr['item'];
		$arr['item'] = array($tmp);
	}
	$project_id = 0;
	foreach($arr['item'] as $data ) {
		$obj = new CTask();
		if (!$obj->bind($data)) {
			echo 'O day 3a';	
			$results['success'] = FALSE;
			$results['messages'] []= 'Server says: Cannot bind data';
			continue;
		}
		$project_id = $obj->task_project;
		if (($msg = $obj->store()) != '') {
			$results['success'] = FALSE;
			$results['messages'] []= $msg;
			continue;
		} else {
			$updateIds []= $obj->task_id;
			$results['messages'][] = 'Store ' . $data['task_description'];
		}
	}
	
	//delete other items:
	if (count($updateIds) > 0) {
		if ($project_id > 0) {
			$checkCostCenter = ' and task_costcenter = ' . $AppUI->user_costcenter;
			$sql = "delete from tasks where task_project = $project_id and task_id not in (" . implode(', ', $updateIds) . ") " . $checkCostCenter;
			db_exec($sql);		
		}
	}	
}

header('Content-Type: text/xml');

$xml = new XmlWriter();
$xml->openMemory();
$xml->startDocument('1.0', 'UTF-8');

$xml->startElement('root');

$xml->writeElement('success', $results['success'] ? 'true' : 'false');
if (count($results['messages']) > 0) {
	$xml->writeElement('messages', addslashes(htmlentities(implode('<br/>', $results['messages']))));
}

$xml->endElement();

echo $xml->outputMemory(true);
?>